<?php

NLoader::register("NApplicationHelper",dirname(__FILE__)."/helper.php");
class NApplication extends NObject {

function isAdmin(){
	return false;
}
function &getInstance ($client,$config=array(),$prefix="N")
	
    // this implements the 'singleton' design pattern.

    {
	
    		static $instances;

		if (!isset( $instances )) {
			$instances = array();
		}

		if (empty($instances[$client]))
		{
			//Load the router object
			$info =& NApplicationHelper::getClientInfo($client, true);
			
			$path = $info->path.DS.'include'.DS.'application.php';
		
			if(file_exists($path))
			{
				require_once $path;

				// Create a JRouter object
				$classname = $prefix.ucfirst($client);
				$instance = new $classname($config);
			}
			else
			{
				$error = NError::raiseError(500, 'Unable to load application: '.$client);
				return $error;
			}

			$instances[$client] =& $instance;
		}

		return $instances[$client];

        

    } // getInstance

function __construct($config){
//set the view name
		$this->_name		= $this->getName();
//Set the default configuration file
		if(!isset($config['config_file'])) {
			$config['config_file'] = 'configuration.php';
		}
	////Enable sessions by default
		if(!isset($config['session'])) {
			$config['session'] = true;
		}	
		//Set the session default name
		if(!isset($config['session_name'])) {
			 $config['session_name'] = $this->_name;
		}
//create the configuration object
	$this->_createConfiguration(NCONFIGUTATION_PATH.DS.$config['config_file']);

		//create the session if a session name is passed
		if($config['session'] !== false) {
			$this->_createSession(NUtility::getHash($config['session_name']));
		}

}
function dispatch(){}
/**
* @DEPRECATED
*/
function initialize(){
//ob_start();
}
function render(){

#$document = NFactory::createDocument($this->config);
$document=NFactory::getDocument();

//ob_clean();
$data =  $document->render();

 NResponse::setBody($data);



}

function login($credential){
	require_once(FRAMEWORK_DIR."/libraries/neocasta/user/authentication.php");
	return  NAuthentication::authenticate($credential);
}

/**
	 * Redirect to another URL.
	 *
	 * Optionally enqueues a message in the system message queue (which will be displayed
	 * the next time a page is loaded) using the enqueueMessage method. If the headers have
	 * not been sent the redirect will be accomplished using a "301 Moved Permanently"
	 * code in the header pointing to the new location. If the headers have already been
	 * sent this will be accomplished using a JavaScript statement.
	 *
	 * @access	public
	 * @param	string	$url	The URL to redirect to.
	 * @param	string	$msg	An optional message to display on redirect.
	 * @param	string  $msgType An optional message type.
	 * @return	none; calls exit().
	 * @since	1.5
	 * @see		JApplication::enqueueMessage()
	 */
	function redirect_smart( $url, $msg='', $msgType='message' )
	{
		// check for relative internal links
		if (preg_match( '#^index[2]?.php#', $url )) {
			$url = NURI::base() . $url;
		}

		// Strip out any line breaks
		$url = preg_split("/[\r\n]/", $url);
		$url = $url[0];

		// If the message exists, enqueue it
		if (trim( $msg )) {
			$this->enqueueMessage($msg, $msgType);
		}

		// Persist messages if they exist
		if (count($this->_messageQueue))
		{
			$session =& NFactory::getSession();
			$session->set('application.queue', $this->_messageQueue);
		}

		/*
		 * If the headers have been sent, then we cannot send an additional location header
		 * so we will output a javascript redirect statement.
		 */
		if (headers_sent()) {
			echo "<script>document.location.href='$url';</script>\n";
		} else {
			//@ob_end_clean(); // clear output buffer
			header( 'HTTP/1.1 301 Moved Permanently' );
			header( 'Location: ' . $url );
		}
		$this->close();
	}


function redirect($url="",$msg="",$time=0){
	if (!$time) $this->redirect_smart($url,$msg); return;
$theme=NFactory::getTheme();
	$theme->module_header.= "<meta http-equiv=\"Refresh\" content=\"$time; URL=$url\"> ";
?>
	
<div class=info><?=$msg?></div>
<div>Если вы не перешли на другую страницу через <b><?=$time?></b> сек. автоматически, то нажмите <a href="<?=$url?>">здесь</a></div>

	
<?php



}


	/**
	 * Redirect to another URL.
	 *
	 * Optionally enqueues a message in the system message queue (which will be displayed
	 * the next time a page is loaded) using the enqueueMessage method. If the headers have
	 * not been sent the redirect will be accomplished using a "301 Moved Permanently"
	 * code in the header pointing to the new location. If the headers have already been
	 * sent this will be accomplished using a JavaScript statement.
	 *
	 * @access	public
	 * @param	string	$url	The URL to redirect to.
	 * @param	string	$msg	An optional message to display on redirect.
	 * @param	string  $msgType An optional message type.
	 * @return	none; calls exit().
	 * @since	1.5
	 * @see		NApplication::enqueueMessage()
	 */
	function redirectsmart( $url, $msg='', $msgType='message' )
	{
		// check for relative internal links
		if (preg_match( '#^index[2]?.php#', $url )) {
			$url = NURI::base() . $url;
		}

		// Strip out any line breaks
		$url = preg_split("/[\r\n]/", $url);
		$url = $url[0];

		// If the message exists, enqueue it
		if (trim( $msg )) {
			$this->enqueueMessage($msg, $msgType);
		}

		// Persist messages if they exist
		if (count($this->_messageQueue))
		{
			$session =& Nactory::getSession();
			$session->set('application.queue', $this->_messageQueue);
		}

		/*
		 * If the headers have been sent, then we cannot send an additional location header
		 * so we will output a javascript redirect statement.
		 */
		if (headers_sent()) {
			echo "<script>document.location.href='$url';</script>\n";
		} else {
			//@ob_end_clean(); // clear output buffer
			header( 'HTTP/1.1 301 Moved Permanently' );
			header( 'Location: ' . $url );
		}
		$this->close();
	}

	/**
	 * Enqueue a system message.
	 *
	 * @access	public
	 * @param	string 	$msg 	The message to enqueue.
	 * @param	string	$type	The message type.
	 * @return	void
	 * @since	1.5
	 */
	function enqueueMessage( $msg, $type = 'message' )
	{

		// For empty queue, if messages exists in the session, enqueue them first
		if (!count($this->_messageQueue))
		{
			$session =& NFactory::getSession();
			$sessionQueue = $session->get('application.queue');
			if (count($sessionQueue)) {
				$this->_messageQueue = $sessionQueue;
				$session->set('application.queue', null);
			}
		}
		// Enqueue the message
		$this->_messageQueue[] = array('message' => $msg, 'type' => strtolower($type));
	}

	/**
	 * Get the system message queue.
	 *
	 * @access	public
	 * @return	The system message queue.
	 * @since	1.5
	 */
	function getMessageQueue()
	{
		// For empty queue, if messages exists in the session, enqueue them
		if (!count($this->_messageQueue))
		{
			$session =&  NFactory::getSession();
			$sessionQueue = $session->get('application.queue');
			if (count($sessionQueue)) {
				$this->_messageQueue = $sessionQueue;
				$session->set('application.queue', null);
			}
		}
		return $this->_messageQueue;
	}

function close( $code = 0 ) {
		exit($code);
	}

/**
	 * Create the configuration registry
	 *
	 * @access	private
	 * @param	string	$file 	The path to the configuration file
	 * return	JConfig
	 */
	function &_createConfiguration($file)
	{
		
		require_once( $file );

		// Create the JConfig object
		$config = new NConfig();

		// Get the global configuration object
		$registry =& NFactory::getConfig();

		// Load the configuration values into the registry
		$registry->loadObject($config);

		return $config;
	}

	/**
	 * Create the user session.
	 *
	 * Old sessions are flushed based on the configuration value for the cookie
	 * lifetime. If an existing session, then the last access time is updated.
	 * If a new session, a session id is generated and a record is created in
	 * the #__sessions table.
	 *
	 * @access	private
	 * @param	string	The sessions name.
	 * @return	object	JSession on success. May call exit() on database error.
	 * @since	1.5
	 */
	function &_createSession( $name )
	{	
		$options = array();
		$options['name'] = $name;

		$session =& NFactory::getSession($options);
		
/*
		nimport('joomla.database.table');
		$storage = & Table::getInstance('session');
		$storage->purge($session->getExpire());*/

		// Session exists and is not expired, update time in session table
// 		if ($storage->load($session->getId())) {
// 			$storage->update();
// 			return $session;
// 		}

		//Session doesn't exist yet, initalise and store it in the session table
		$session->set('registry',	new NRegistry('session'));
		$session->set('user',		new NUser());

// 		if (!$storage->insert( $session->getId(), $this->getClientId())) {
// 			jexit( $storage->getError());
// 		}

		return $session;
	}

/**
	 * Method to get the application name
	 *
	 * The dispatcher name by default parsed using the classname, or it can be set
	 * by passing a $config['name'] in the class constructor
	 *
	 * @access	public
	 * @return	string The name of the dispatcher
	 * @since	1.5
	 */
	function getName()
	{
		$name = $this->_name;

		if (empty( $name ))
		{
			$r = null;
			if ( !preg_match( '/N(.*)/i', get_class( $this ), $r ) ) {
				NError::raiseError(500, "JApplication::getName() : Can\'t get or parse class name.");
			}
			$name = strtolower( $r[1] );
		}

		return $name;
	}

	function triggerEvent($event, $args=null)
	{
		$dispatcher =& NDispatcher::getInstance();
		return $dispatcher->trigger($event, $args);
	}

	function registerEvent($event, $handler)
	{
		$dispatcher =& NDispatcher::getInstance();
		$dispatcher->register($event, $handler);
	}
	/**
	 * Gets the name of the current template.
	 *
	 * @return	string
	 */
	function getTemplate()
	{
		return 'system';
	}

}
?>